package com.cloudcc.mobile.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import com.cloudcc.mobile.entity.User;
import com.cloudcc.mobile.entity.UserMessage;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.login.LoginNewActivity;

public class UserParser {
	/**
	 * 解析查询的企业通讯录
	 * @param jsonString
	 * @return
	 */
	public  static UserMessage getUsers(String jsonString){
		ArrayList<User> list=new ArrayList<User>();
		UserMessage message=new UserMessage();
		try {
			JSONObject obj=new JSONObject(jsonString);
			message.setResult(obj.getBoolean("result"));
			message.setReturnInfo(obj.getString("returnInfo"));
			message.setReturnCode(obj.getInt("returnCode"));
			JSONArray json=obj.getJSONArray("data");
			for (int i = 0; i < json.length(); i++) {
				JSONObject jsonObj=json.getJSONObject(i);
				User user=(User)Json.toObject(jsonObj.toString(),User.class);
				list.add(user);
			}
			message.setList(list);
		} catch (JSONException e) {
			Tools.handle(e);
		}
		return message;
	}

	public static Map<String,User> getAllCallRecords(Context context,String jsonString) {
		UserMessage userMessage=getUsers(jsonString);
		if(!userMessage.isResult()){
			return null;
		}else if(userMessage.getReturnCode()==-2){
			Intent intent=new Intent(context,LoginNewActivity.class);
			context.startActivity(intent);
		}
		List<User> user=userMessage.getList();
		Map<String,User> map=new HashMap<String, User>();
		if(user!=null){
			for (int i = 0; i < user.size(); i++) {
				String name=user.get(i).getName();
				map.put(name, user.get(i));
			}
			return map;
		}
		return null;
	}
}
